package com.zhuliwei.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.ChangeCommentStatusDto;
import com.zhuliwei.domain.dto.CommentListDto;
import com.zhuliwei.domain.entity.Comment;
import com.zhuliwei.domain.vo.CommentListVo;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.service.CommentService;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.WebUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.zhuliwei.constants.RabbitConstants.*;

/**
 * 审核管理相关接口
 *
 * @author 朱力维
 * @time 2022/11/15 16:20
 **/
@RestController
@RequestMapping("/content/comment")
public class CommentController {
    @Resource
    private CommentService commentService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('content:comment:list')")
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, CommentListDto commentDto) {
        return commentService.getAllComment(pageNum, pageSize, commentDto);
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@ps.hasPermission('content:comment:delete')")
    public ResponseResult del(@PathVariable List<String> ids) {
        commentService.removeByIds(ids);
        return ResponseResult.okResult();
    }

    @PutMapping("/changeCommentStatus")
    @Transactional
    @PreAuthorize("@ps.hasPermission('content:comment:audit')")
    public ResponseResult changeCommentStatus(@RequestBody ChangeCommentStatusDto commentDto) {
        // 状态为未审核的才可以更改审核状态
        commentDto.getStatusList().forEach(item -> {
            if (!item.equals("2")) {
                throw new SystemException(AppHttpCodeEnum.AUDIT_ERROR);
            }
        });
        for (String id : commentDto.getIds()
        ) {
            Comment comment = commentService.getById(id);
            comment.setStatus(commentDto.getNewStatus());
            // 审核后通知用户审核成功或失败（异步）
            rabbitTemplate.convertAndSend(NOTICE_EXCHANGE_NAME, NOTICE_AUDIT_KEY, comment);
            // 审核为通过且不为根评论才通知被回复的用户收到一条回复（异步）
            if (commentDto.getNewStatus().equals("0") && !comment.getToCommentId().equals("-1") && StringUtils.hasText(comment.getToCommentId())) {
                if (StringUtils.hasText(comment.getToCommentId())) {
                    rabbitTemplate.convertAndSend(NOTICE_EXCHANGE_NAME, NOTICE_ROUTING_KEY, comment);
                }
            }
            commentService.updateById(comment);
        }
        return ResponseResult.okResult();
    }

    @PreAuthorize("@ps.hasPermission('content:comment:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("评论.xlsx", response);
            //获取需要导出的数据
            List<Comment> comments = commentService.list();
            List<CommentListVo> commentListVos = BeanCopyUtils.copyBeanList(comments, CommentListVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), CommentListVo.class).autoCloseStream(Boolean.FALSE).sheet("评论导出")
                    .doWrite(commentListVos);
        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
